package com.njtoyo.taxi.admin.rest.readfile.driver;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.njtoyo.taxi.admin.library.common.util.CopyUtil;
import com.njtoyo.taxi.admin.logic.business.driver.DriverLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.Driver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class DriverSwitchTaxiListener extends AnalysisEventListener<DriverSwitchTaxiData> {

    private static final Logger LOGGER = LoggerFactory.getLogger(DriverRegisterListener.class);

    private final DriverSwitchTaxiResult result = new DriverSwitchTaxiResult();
    private final DriverLogic driverLogic;
    private final List<Driver> successResult = new ArrayList<>();
    private final List<DriverSwitchTaxiResult.FailData> failResult = new ArrayList<>();

    public DriverSwitchTaxiListener(DriverLogic driverLogic) {
        this.driverLogic = driverLogic;
    }

    @Override
    public void invoke(DriverSwitchTaxiData driverSwitchTaxiData, AnalysisContext analysisContext) {
        this.result.setUploadCount(this.result.getUploadCount() + 1);
        try {
            Long id = driverSwitchTaxiData.getId();
            String plateNumber = driverSwitchTaxiData.getPlateNumber();
            Driver driver = driverLogic.switchTaxi(id,plateNumber);
            this.successResult.add(driver);
            this.result.setSuccessCount(this.result.getSuccessCount() + 1);
        } catch (Exception e) {
            DriverSwitchTaxiResult.FailData failData = CopyUtil.copy(driverSwitchTaxiData, DriverSwitchTaxiResult.FailData.class);
            failData.setMessage(e.getMessage());
            this.failResult.add(failData);
            this.result.setFailCount(this.result.getFailCount() + 1);
        }
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.result.setSuccessResult(this.successResult);
        this.result.setFailResult(this.failResult);
    }

    public DriverSwitchTaxiResult getResult() {
        return result;
    }
}
